package com.aoyebobi.baseDemo.client;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @Description
 * @Author aoyebobi
 * @Date 2024-09-03
 */

public class AppServerHello {

    private int port;

    public AppServerHello(int port) {
        this.port = port;
    }

    public void run() throws Exception{
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            //服务端辅助启动类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置线程组
            serverBootstrap.group(group)
                    .channel(NioServerSocketChannel.class)
                    //监听的端口
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //配置handler
                            socketChannel.pipeline().addLast(new HandleServerHello());
                        }
                    });

            //绑定服务器，该实例将提供有关IO操作的结果或状态的信息
            ChannelFuture future = serverBootstrap.bind().sync();

            System.out.println("在"+ future.channel().localAddress()+"上开启监听");

            //阻塞操作，closeFuture()开启了一个channel的监听器（这期间channel在进行各项工作），直到链路断开
            future.channel().closeFuture().sync();
        }finally {
            //关闭EventLoopGroup并释放所有资源，包括所有创建的线程
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args)  throws Exception
    {
        new AppServerHello(18080).run();
    }
}
